from django.db.models import permalink
from django.utils import translation
from django.forms import Field

from google.appengine.ext import db

from functools import wraps
from itertools import imap as map
from itertools import izip as zip

def _loc_get_absolute_url(method):
    @wraps(method)
    def wrapper(self):
        result = method(self)
        result[2]['lang_code'] = translation.get_language()
        return result
    return wrapper
    
def _set_property_for_models(models, prop_name, prop_factory):
    if not isinstance(models, (list, tuple)):
        models = list(models)
    
    for model in models:
        #<prop_name> is used here as an indicator that the model
        #will be localized. If everything goes well, <prop_name>
        #will become a property.
        #!!! if model.__dict__.get(prop_name, model) is not model
        setattr(model, prop_name, model)
    
    for model in models:
        if prop_name not in model.__dict__:
            continue
        mod = model
        while True:
            delattr(mod, prop_name)
            if not hasattr(model, prop_name):
                setattr(model, prop_name, model)
                break
            elif hasattr(mod, prop_name):
                mod = getattr(mod, prop_name)  
            else:
                raise db.DuplicatePropertyError("%s is inherited by %s from both %s and %s." %
                                                (prop_name, model.__name__, mod.__name__,
                                                 model.lang_code.__name__))
    
    for model in models:
        if prop_name in model.__dict__:
            property = prop_factory()
            setattr(model, prop_name, property)
            property.__property_config__(model, prop_name)
        model._properties[prop_name] = property
        

def _localize_model(model):
    # localize get_absolute_url
    get_absolute_url = model.__dict__.get('get_absolute_url')
    if get_absolute_url:
        model.get_absolute_url = permalink(_loc_get_absolute_url(get_absolute_url))
        
    

    
#props = getattr(model, 'multilingual', None) ...
#add lput, ldelete for storing and deleting multilingual properties 


def localize_all_models(all_names, globals):
    models = [globals[n] for n in all_names]
    
    _set_property_for_models(models, 'lang_code', LanguageProperty) #!!
    
    for model in models:
        _localize_model(model)
        
        
        
    
    
    
    
    
        
    